package be.kuleuven.mume.rest;

import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import be.kuleuven.mume.JSONHelper;
import be.kuleuven.mume.beans.AgendaBean;
import be.kuleuven.mume.beans.AgendaBean.AgendaBeanFactory;
import be.kuleuven.mume.beans.PersoonBean;
import be.kuleuven.mume.exceptions.UserNotLoggedInException;
import be.kuleuven.mume.query.PersoonQuery;

import com.google.appengine.api.datastore.KeyFactory;

@Path("/agenda")
public class Agenda {
	private static final Logger log = Logger.getLogger(Vraag.class.getName());
	
	@GET
	@Path("/")
	@Produces ("application/json")
	public String getAfspraken(@PathParam("type") String type, @QueryParam("rpp")@DefaultValue("10") long rpp, 
			@QueryParam("page")@DefaultValue("0") long page) {
		try{

			JSONArray array = new JSONArray();
			PersoonBean persoon = PersoonQuery.getCurrentPersoon();
			List<AgendaBean> afspraken = AgendaBeanFactory.getAfspraken(persoon, page, rpp);

			for (AgendaBean agendaBean : afspraken) {
				array.put((new JSONObject(agendaBean)));
			}
			
			JSONObject result = new JSONObject();
			result.put("result", array);

			return result.toString();

		} catch (Exception e){
			log.log(Level.SEVERE,"Exception",e);
		} /*catch (UserNotLoggedInException e) {
			return e.toJsonString();
		}*/

		return JSONHelper.ERROR;
	}
	
	@GET
	@Path("/updates")
	@Produces ("application/json")
	public String getUpdates(@QueryParam("rpp")@DefaultValue("10") long rpp, 
			@QueryParam("page")@DefaultValue("0") long page) {
		try{
			JSONArray array = new JSONArray();
			PersoonBean persoon = PersoonQuery.getCurrentPersoon();
			List<AgendaBean> afspraken = AgendaBeanFactory.getUpdates(persoon, page, rpp);

			for (AgendaBean agendaBean : afspraken) {
				array.put((new JSONObject(agendaBean)));
			}
			
			JSONObject result = new JSONObject();
			result.put("result", array);

			return result.toString();

		} catch (Exception e){
			log.log(Level.SEVERE,"Exception",e);
		} /*catch (UserNotLoggedInException e) {
			return e.toJsonString();
		}*/

		return JSONHelper.ERROR;
	}
	
	private Calendar getDate(String date, String time) {
		String[] dates = date.split("-");
		String[] times = time.split(":");
		Calendar calendar = Calendar.getInstance();
		//google chrome:
		calendar.set(Integer.parseInt(dates[0]), Integer.parseInt(dates[1])-1, Integer.parseInt(dates[2]), Integer.parseInt(times[0]), Integer.parseInt(times[1]),0);
		//device:
		//calendar.set(Integer.parseInt(dates[2]), Integer.parseInt(dates[0])-1, Integer.parseInt(dates[2]), Integer.parseInt(times[1]), Integer.parseInt(times[1]),0);
		return calendar;
	}
	
	private int getDigits(String string) {
		if(string == "")
			return 0;
		else
			return Integer.parseInt(string);
	}
	
	@Path("/add/uurrooster")
	@POST
	@Produces("application/json")
	@Consumes ("application/json")
	public String addLes(String lesJson){
		try {
			JSONObject object = new JSONObject(lesJson);
			String date = object.getString("date");
			String time = object.getString("time");
			AgendaBean afspraak = new AgendaBean(getDate(date,time),"uurrooster");
			afspraak.setHours(getDigits(object.getString("duur")));
			afspraak.setMinutes(getDigits(object.getString("duur_min")));
			afspraak.setLocatie(object.getString("locatie"));
			afspraak.setOmschrijving(object.getString("omschrijving"));
			afspraak.setVakId(KeyFactory.stringToKey(object.getString("vakId")));
			afspraak.store();
		} catch (JSONException e) {
			log.log(Level.SEVERE, "Exception", e);
		}
		return JSONHelper.ERROR;
	}
	
	@Path("/add/deadline")
	@POST
	@Produces("application/json")
	@Consumes ("application/json")
	public String addDeadline(String lesJson){
		try {
			JSONObject object = new JSONObject(lesJson);
			String date = object.getString("date");
			String time = object.getString("time");
			AgendaBean afspraak = new AgendaBean(getDate(date,time),"deadline");
			afspraak.setOmschrijving(object.getString("omschrijving"));
			afspraak.setVakId(KeyFactory.stringToKey(object.getString("vakId")));
			afspraak.store();
		} catch (JSONException e) {
			log.log(Level.SEVERE, "Exception", e);
		}
		return JSONHelper.ERROR;
	}
	
	@Path("/add/afspraak")
	@POST
	@Produces("application/json")
	@Consumes ("application/json")
	public String addAfspraak(String lesJson) throws UserNotLoggedInException{
		try {
			JSONObject object = new JSONObject(lesJson);
			String date = object.getString("date");
			String time = object.getString("time");
			String type;
			if(object.has("persoon"))
				type = "afspraak";
			else type = "vrije_tijd";
			AgendaBean afspraak = new AgendaBean(getDate(date,time),type);
			afspraak.setHours(getDigits(object.getString("duur")));
			afspraak.setMinutes(getDigits(object.getString("duur_min")));
			afspraak.setLocatie(object.getString("locatie"));
			afspraak.setOmschrijving(object.getString("omschrijving"));
			afspraak.setUserId(KeyFactory.stringToKey(PersoonQuery.getCurrentPersoon().getId()));
			if(object.has("persoon"))
				afspraak.setMet(object.getString("persoon"));
			afspraak.store();
		} catch (JSONException e) {
			log.log(Level.SEVERE, "Exception", e);
		}
		return JSONHelper.ERROR;
	}
}
